//
//  ComposeViewController.swift
//  weibo
//
//  Created by 张宏芝 on 15/9/10.
//  Copyright © 2015年 kama. All rights reserved.
//

import UIKit
import SVProgressHUD

private let HZStatusTextMaxLength = 10

// 设定代理
class ComposeViewController: UIViewController,UITextViewDelegate {

    //    MARK:懒加载
    private lazy var keyboardVC:EmoticonViewController = EmoticonViewController {[weak self](emoticon) -> () in
        self?.textView.insertEmoticon(emoticon)
    }
    
    @objc private func switchEmoticonKeyboard(){
//        注销焦点
        textView.resignFirstResponder()
//        切换键盘
        textView.inputView = (textView.inputView == nil) ? keyboardVC.view :nil
//        激活焦点
        textView.becomeFirstResponder()
    }
    
    
//    MARK:控件动画约束---工具底部约束
    private var toolbarBottomCons:NSLayoutConstraint?
    /// 文本视图底部约束
    private var textViewBottomCons: NSLayoutConstraint?
    /// 照片选择视图的高度约束
    private var pictureViewHeightCons: NSLayoutConstraint?

    
//   点击取消,关闭控制器
    @objc private func close(){
//        退出是键盘也跟着退出
        textView.resignFirstResponder()
        dismissViewControllerAnimated(true, completion: nil)
    }
//    点击发送微博
    @objc private func sendStatus(){
        let text = textView.emoticonText
        NetWorkTools.sharedTools.sendStatus(text).subscribeNext({ (result) -> Void in
            
            }, error: { (error) -> Void in
                SVProgressHUD.showInfoWithStatus("您的网络不给力")
            }) { () -> Void in
                self.close()
        }    }
    @objc private func selectPicture(){
        print("点击了插入图片按钮")
        // 1. 删除文本视图和 toolbar 之间的约束
        view.removeConstraint(textViewBottomCons!)
        
        // 2. 设置文本视图和照片视图之间的约束
        textViewBottomCons = NSLayoutConstraint(item: textView, attribute: NSLayoutAttribute.Bottom, relatedBy: NSLayoutRelation.Equal, toItem: pictureSelectorVC.view, attribute: NSLayoutAttribute.Top, multiplier: 1.0, constant: 0)
        view.addConstraint(textViewBottomCons!)
        
        // 3. 设置高度约束
        pictureViewHeightCons?.constant = UIScreen.mainScreen().bounds.height * 0.6
        
        // 4. 关闭键盘
        textView.resignFirstResponder()
        
        // 5. 动画更新约束
        UIView.animateWithDuration(0.25) {
            self.view.layoutIfNeeded()
        }

    }
    
//    MARK:---UITextViewDelegate代理
    func textViewDidChange(textView: UITextView) {
        placeholderlabel.hidden = textView.hasText()
        navigationItem.rightBarButtonItem?.enabled = textView.hasText()
    }
    
//    MARK:----视图生命周期函数
    override func viewDidLoad() {
        super.viewDidLoad()
//        注册键盘通知
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardChanged:", name: UIKeyboardWillChangeFrameNotification, object: nil)
    }
    deinit{
//        注销通知
        NSNotificationCenter.defaultCenter().removeObserver(self)
    }
//    键盘变化监听方法
    @objc private func keyboardChanged(n:NSNotification){
        
//        获取动画属性数组
//        1. 获取动画曲线设置为7,在连续的动画过程中,前一个动画如果没有执行完毕,直接过度到最后一个动画
//        2.使用7之后,动画时间一律变成0.5s
        
        let curve = n.userInfo![UIKeyboardAnimationCurveUserInfoKey]!.integerValue
        
//        获取最终的frame---oc中将结构保存在字典中,存成NSValue
        let rect = n.userInfo![UIKeyboardFrameEndUserInfoKey]!.CGRectValue
//        获取动画的时长
        let duration = n.userInfo![UIKeyboardAnimationDurationUserInfoKey]!.doubleValue
        toolbarBottomCons?.constant = -UIScreen.mainScreen().bounds.height + rect.origin.y

//        UIView的块动画,本质上是一个"核心动画"的封装
//        核心概念:1.通过keyPath来指定壳动画属性的数值
//        2.将动画添加到"图层"
        UIView.animateWithDuration(duration){
            
//            设置动画属性
            UIView.setAnimationCurve(UIViewAnimationCurve.init(rawValue: curve)!)
            self.view.layoutIfNeeded()
        }
    }
    override func viewDidAppear(animated: Bool) {
        super.viewDidAppear(animated)
//        激活键盘
//        textView.becomeFirstResponder()
        // 判断如果用户已经选择了照片，就不再激活键盘，> 0 说明已经选择了照片
        if pictureViewHeightCons?.constant == 0 {
            // 激活键盘
            textView.becomeFirstResponder()
        }

    }
    
//    创建界面UI
    override func loadView() {
        view = UIView()
        
        // 将自动调整 scrollView 的缩进取消
        automaticallyAdjustsScrollViewInsets = false

        view.backgroundColor = UIColor.whiteColor()
        
        preparNav()
        prepartoolBar()
        prepartextView()
        preparePictureView()
    }
    
    /// 准备照片视图
    private func preparePictureView() {
        // 0. 添加子控制器 － 提示：实际开发中发现响应者链条无法正常传递，通常就是忘记添加子控制器
        // storyboard 中有一个 containerView，纯代码中没有这个控件
        // 本质上就是一个 UIView
        // 1> addSubView(vc.view)
        // 2> addChildViewController(vc)
        addChildViewController(pictureSelectorVC)
        

        
        // 1. 添加视图
//        view.addSubview(pictureSelectorVC.view)
        view.insertSubview(pictureSelectorVC.view, belowSubview: toolBar)

        
        // 2. 自动布局
        let size = UIScreen.mainScreen().bounds.size
        let w = size.width
//        let h = size.height * 0.6
//        pictureSelectorVC.view.ff_AlignInner(type: ff_AlignType.BottomLeft, referView: view, size: CGSize(width: w, height: h))
        let h: CGFloat = 0 //size.height * 0.6
        let cons = pictureSelectorVC.view.ff_AlignInner(type: ff_AlignType.BottomLeft, referView: view, size: CGSize(width: w, height: h))
        // 记录照片视图的高度约束
        pictureViewHeightCons = pictureSelectorVC.view.ff_Constraint(cons, attribute: NSLayoutAttribute.Height)

    }

    
//    nav导航条的准备工作
    private func preparNav(){
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "取消", style: UIBarButtonItemStyle.Plain, target: self, action: "close")
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "发送", style: UIBarButtonItemStyle.Plain, target: self, action: "sendStatus")
        navigationItem.rightBarButtonItem?.enabled = false
//        标题视图
        let titleView = UIView(frame: CGRect(x: 0, y: 0, width: 200, height: 32))
        let titleLabel = UILabel(title: "发微博", color: UIColor.darkGrayColor(), fontSize: 15)
        let nameLabel = UILabel(title: UserAccountViewModel.sharedUserAccount.userAccount?.name, color: UIColor.lightGrayColor(), fontSize: 13)
        
        titleView.addSubview(titleLabel)
        titleView.addSubview(nameLabel)

        titleLabel.ff_AlignInner(type: ff_AlignType.TopCenter, referView: titleView, size: nil)
        nameLabel.ff_AlignInner(type: ff_AlignType.BottomCenter, referView: titleView, size: nil)
//      导航控制器的标题的view
        navigationItem.titleView = titleView
    }
    
//    toolBar的准备工作
    private func prepartoolBar(){
        view.addSubview(toolBar)
        toolBar.backgroundColor = UIColor(white: 0.8, alpha: 1.0)
        
//        自动布局
        let width = UIScreen.mainScreen().bounds.width
//        toolBar.ff_AlignInner(type: ff_AlignType.BottomLeft, referView: view, size: CGSize(width: width, height: 44))
        let cons = toolBar.ff_AlignInner(type: ff_AlignType.BottomLeft, referView: view, size: CGSize(width: width, height: 44))
//        记录底部结束
        toolbarBottomCons = toolBar.ff_Constraint(cons, attribute: NSLayoutAttribute.Bottom)
//        确认获得的约束
        printLog(toolbarBottomCons)
        
        // 定义按钮数组
        let itemSettings = [["imageName": "compose_toolbar_picture", "action": "selectPicture"],
            ["imageName": "compose_mentionbutton_background"],
            ["imageName": "compose_trendbutton_background"],
            ["imageName": "compose_emoticonbutton_background","action":"switchEmoticonKeyboard"],
            ["imageName": "compose_addbutton_background"]]
        
        // 添加按钮
        var items = [UIBarButtonItem]()
        
        for dict in itemSettings {
            items.append(UIBarButtonItem(imageName: dict["imageName"]!, target: self, actionName: dict["action"]))
            items.append(UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.FlexibleSpace, target: nil, action: nil))
        }
        items.removeLast()
        toolBar.items = items
    }
    
//    文本标签,占位符,文字一起拖动
    private func prepartextView(){
        
        view.addSubview(textView)
//        自动布局
        textView.translatesAutoresizingMaskIntoConstraints = false
        let viewDict:[String:AnyObject] = ["top":topLayoutGuide,"tb":toolBar,"tv":textView]
        view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-0-[tv]-0-|", options: [], metrics: nil, views: viewDict))
//        view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|-0-[top]-0-[tv]-0-[tb]", options: [], metrics: nil, views: viewDict))
        view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|-0-[top]-0-[tv]", options: [], metrics: nil, views: viewDict))
        
        // 定义 textView 和 toolbar 之间的约束
        textViewBottomCons = NSLayoutConstraint(item: textView, attribute: NSLayoutAttribute.Bottom, relatedBy: NSLayoutRelation.Equal, toItem: toolBar, attribute: NSLayoutAttribute.Top, multiplier: 1.0, constant: 0)
        view.addConstraint(textViewBottomCons!)

        
        textView.addSubview(placeholderlabel)
        placeholderlabel.frame = CGRect(origin: CGPoint(x: 5, y: 8), size: placeholderlabel.bounds.size)

    }
    
//    MARK:懒加载控件
    private lazy var toolBar = UIToolbar()
    
    /// 照片选择控制器
    private lazy var pictureSelectorVC = PictureSelectorViewController()

//    文本视图
    private lazy var textView:UITextView = {
        
        let tv = UITextView()
        tv.delegate = self
//        tv.text = "分享新鲜事...."
        tv.textColor = UIColor.blackColor()
//        文字与UITextView一起拖拽
        tv.alwaysBounceVertical = true
        tv.font = UIFont.systemFontOfSize(18)
//        拖拽的时候关闭键盘
        tv.keyboardDismissMode = UIScrollViewKeyboardDismissMode.OnDrag
        return tv
    }()
//    占位文本
    private lazy var placeholderlabel:UILabel = UILabel(title: "分享新鲜事....", color: UIColor.lightGrayColor(), fontSize: 18)
}
